<template>
  <CommonTable :tableInfo="tableInfo"
               :insertTableInfo="insertTableInfo"
               :notUpdate="notUpdate"
               :notDelete="notDelete"
               :notInsert="notInsert"
               @onTableReq="tableReq"
               @onInsertReq="insertReq"
               @onDeleteReq="deleteReq"
               @onUpdateReq="updateReq"
               :stock="stock"
  >
  </CommonTable>
</template>

<script lang="ts" setup>
import axios from "axios";

import CommonTable from "@/components/common/CommonTable.vue";
import {ElMessage} from "element-plus";

const props = defineProps(['tableInfo', "insertTableInfo", "tableReqUrl", "notUpdate", "notDelete", "notInsert",'stock']);
const emit = defineEmits(["onGetDeleteReqUrl"]);

// 检测是否为对象
const isObject = (variable) => {
  return variable !== null && typeof variable === 'object' && !Array.isArray(variable);
}

// 将item对象中的值全部变为同一层
const convertOne = (item) => {
  for (const itemKey in item) {
    // 为对象类型
    if (isObject(item[itemKey])) {
      let temp = item[itemKey];
      for (const tempKey in temp) {
        item[tempKey] = temp[tempKey];
      }
      item[itemKey] = null;
    }

  }

}
// 获取列表
const tableReq = async (reFun) => {
  // 读取管理员列表
  const {data} = await axios.get(props.tableReqUrl);
  if (data.code === 200) {
    data.data.forEach((item) => {
      convertOne(item)
    })
    // console.log(data.data)
    reFun(data.data);
  }
}

// 插入请求
const insertReq = async ({value, callback}) => {
  const {data} = await axios.post(props.tableReqUrl, value);
  if (data.code === 200) {
    ElMessage.success("添加成功");
    callback();
  }
};

// 删除请求
const deleteReq = async ({value, callback}) => {
  let deleteUrl = "";
  await emit("onGetDeleteReqUrl", {value, reFun: (data) => deleteUrl = data});
  const {data} = await axios.delete(deleteUrl);
  if (data.code === 200) {
    ElMessage.success("删除成功");
    callback();
  }
};

// 修改请求
const updateReq = async ({value, callback}) => {
  const {data} = await axios.put(props.tableReqUrl, value);
  if (data.code === 200) {
    ElMessage.success("修改成功");
    callback();
  }
};


</script>

<style scoped>

</style>